package com.wonders.springboot.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private DataSource dataSource;

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new
                JdbcTokenRepositoryImpl();
// 赋值数据源
        jdbcTokenRepository.setDataSource(dataSource);
// 自动创建表,第一次执行会创建，以后要执行就要删除掉！
//        jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 开启记住我功能
        http.rememberMe()
                .tokenValiditySeconds(60)//设置记住我的时间是60秒
                .tokenRepository(persistentTokenRepository())
                .userDetailsService(userDetailsService);

        //设置没有权限，跳转的自定义网页
        http.exceptionHandling().accessDeniedPage("/unauth");

        //配置没有权限访问跳转自定义页面
        http.authorizeRequests()
                .antMatchers("/index", "/failer", "/unauth", "/css/**", "/img/**", "/js/**")
                .permitAll()//都不需要认证
//                .antMatchers("/**").hasAnyRole("管理员")//底层会加上一个ROLE_前缀。
                .anyRequest()//其他任何请求
                .authenticated()//都需要认证通过
                .and()
                .formLogin()   //自定义自己编写的登录页面
                .loginPage("/index")  //登录页面设置
                .loginProcessingUrl("/login")   //登录访问路径
                .defaultSuccessUrl("/success")  //登录成功之后，跳转路径
                .failureUrl("/failer")//登录失败之后，跳转路径
                .and()
                .logout()//退出登录
                .logoutUrl("/logout")
                .invalidateHttpSession(true)
                .logoutSuccessUrl("/index")
                .permitAll()
                .and().csrf().disable();  //关闭csrf防护
    }
}
